<?php

/**
 * comment actions.
 *
 * @package    blogallery
 * @subpackage comment
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 2692 2006-11-15 21:03:55Z fabien $
 */
class commentActions extends sfActions
{
  /**
   * Executes index action
   *
   */
  public function executeIndex()
  {
    $this->forward('comment', 'list');
  }
  
  public function executeAdd()
  {
  	if ($this->getUser()->getParameter('new_comment_disallow') < strtotime('now'))
  	{
  	  if ($this->getRequest()->getMethod() === sfRequest::POST)
  	  {
  	    $post = PostPeer::retrieveByPk($this->getRequestParameter('id'));
  	    $this->forward404Unless($post instanceof Post);
  	    $this->forward404Unless($post->getCommentAllow());
  	    
  	    $comment = new Comment();
  	    $comment->setPostId($post->getId());
  	    $comment->setIp($_SERVER['REMOTE_ADDR']);
  	    $comment->setName($this->getRequestParameter('name'));
  	    $comment->setEmail($this->getRequestParameter('email'));
  	    $comment->setUrl($this->getRequestParameter('url'));
  	    $comment->setContent(myTools::filterHtml($this->getRequestParameter('content')));
  	    $comment->setDatetime(strftime('%Y-%m-%d %H:%M:%S'));
  	    $comment->setApproved((sfConfig::get('app_comment_autoapprove')) ? '1' : '0');
  	    
  	    if ($this->getUser()->isAuthenticated())
  	    {
  	      $comment->setUserId($this->getUser()->getUserId());
  	    }
  	    
  	    $comment->save();
  	  
  	    $this->getUser()->setParameter('new_comment_disallow', strtotime('now') + sfConfig::get('app_comment_timeout')*60, 'subscriber');
  	  }
  	}
  	
  	$this->redirect('@default?lang='.$this->getUser()->getLang().'&module=post&action=show&handle='.$post->getHandle());
  }
  
  public function handleErrorAdd()
  {
  	$post = PostPeer::retrieveByPk($this->getRequestParameter('id'));
  	$this->forward404Unless($post instanceof Post);
  	
  	$this->post = $post;  	
  }

  public function executeList()
  {
    $this->processSort();

    $this->processFilters();

    $this->filters = $this->getUser()->getAttributeHolder()->getAll('sf_admin/comment/filters');

    // pager
    $this->pager = new sfPropelPager('Comment', 20);
    $c = new Criteria();
    $this->addSortCriteria($c);
    $this->addFiltersCriteria($c);
    $this->pager->setCriteria($c);
    $this->pager->setPage($this->getRequestParameter('page', 1));
    $this->pager->init();
  }

  public function executeCreate()
  {
    return $this->forward('comment', 'edit');
  }

  public function executeSave()
  {
    return $this->forward('comment', 'edit');
  }

  public function executeEdit()
  {
    $this->comment = $this->getCommentOrCreate();

    if ($this->getRequest()->getMethod() == sfRequest::POST)
    {
      $this->updateCommentFromRequest();

      $this->saveComment($this->comment);

      $this->setFlash('notice', 'Your modifications have been saved');

      if ($this->getRequestParameter('save_and_add'))
      {
        return $this->redirect('@admin?module=comment&action=create');
      }
      else if ($this->getRequestParameter('save_and_list'))
      {
        return $this->redirect('@admin?module=comment&action=list');
      }
      else
      {
        return $this->redirect('@admin?module=comment&action=edit?id='.$this->comment->getId());
      }
    }
    else
    {
      $this->labels = $this->getLabels();
    }
  }

  public function executeDelete()
  {
    $this->comment = CommentPeer::retrieveByPk($this->getRequestParameter('id'));
    $this->forward404Unless($this->comment);

    try
    {
      $this->deleteComment($this->comment);
    }
    catch (PropelException $e)
    {
      $this->getRequest()->setError('delete', 'Could not delete the selected Comment. Make sure it does not have any associated items.');
      return $this->forward('comment', 'list');
    }

    return $this->redirect('@admin?module=comment&action=list');
  }

  public function handleErrorEdit()
  {
    $this->preExecute();
    $this->comment = $this->getCommentOrCreate();
    $this->updateCommentFromRequest();

    $this->labels = $this->getLabels();

    return sfView::SUCCESS;
  }

  protected function saveComment($comment)
  {
    $comment->save();

  }

  protected function deleteComment($comment)
  {
    $comment->delete();
  }

  protected function updateCommentFromRequest()
  {
    $comment = $this->getRequestParameter('comment');

    if (isset($comment['name']))
    {
      $this->comment->setName($comment['name']);
    }
    if (isset($comment['url']))
    {
      $this->comment->setUrl($comment['url']);
    }
    if (isset($comment['content']))
    {
      $this->comment->setContent($comment['content']);
    }
    if (isset($comment['approved']))
    {
      $this->comment->setApproved($comment['approved']);
    }
  }

  protected function getCommentOrCreate($id = 'id')
  {
    if (!$this->getRequestParameter($id))
    {
      $comment = new Comment();
    }
    else
    {
      $comment = CommentPeer::retrieveByPk($this->getRequestParameter($id));

      $this->forward404Unless($comment);
    }

    return $comment;
  }

  protected function processFilters()
  {
    if ($this->getRequest()->hasParameter('filter'))
    {
      $filters = $this->getRequestParameter('filters');
      if (isset($filters['datetime']['from']) && $filters['datetime']['from'] !== '')
      {
        $filters['datetime']['from'] = sfI18N::getTimestampForCulture($filters['datetime']['from'], $this->getUser()->getCulture());
      }
      if (isset($filters['datetime']['to']) && $filters['datetime']['to'] !== '')
      {
        $filters['datetime']['to'] = sfI18N::getTimestampForCulture($filters['datetime']['to'], $this->getUser()->getCulture());
      }

      $this->getUser()->getAttributeHolder()->removeNamespace('sf_admin/comment/filters');
      $this->getUser()->getAttributeHolder()->add($filters, 'sf_admin/comment/filters');
    }
  }

  protected function processSort()
  {
    if ($this->getRequestParameter('sort'))
    {
      $this->getUser()->setAttribute('sort', $this->getRequestParameter('sort'), 'sf_admin/comment/sort');
      $this->getUser()->setAttribute('type', $this->getRequestParameter('type', 'asc'), 'sf_admin/comment/sort');
    }

    if (!$this->getUser()->getAttribute('sort', null, 'sf_admin/comment/sort'))
    {
    }
  }

  protected function addFiltersCriteria($c)
  {
    if (isset($this->filters['content_is_empty']))
    {
      $criterion = $c->getNewCriterion(CommentPeer::CONTENT, '');
      $criterion->addOr($c->getNewCriterion(CommentPeer::CONTENT, null, Criteria::ISNULL));
      $c->add($criterion);
    }
    else if (isset($this->filters['content']) && $this->filters['content'] !== '')
    {
      $c->add(CommentPeer::CONTENT, strtr($this->filters['content'], '*', '%'), Criteria::LIKE);
    }
    if (isset($this->filters['datetime_is_empty']))
    {
      $criterion = $c->getNewCriterion(CommentPeer::DATETIME, '');
      $criterion->addOr($c->getNewCriterion(CommentPeer::DATETIME, null, Criteria::ISNULL));
      $c->add($criterion);
    }
    else if (isset($this->filters['datetime']))
    {
      if (isset($this->filters['datetime']['from']) && $this->filters['datetime']['from'] !== '')
      {
        $criterion = $c->getNewCriterion(CommentPeer::DATETIME, $this->filters['datetime']['from'], Criteria::GREATER_EQUAL);
      }
      if (isset($this->filters['datetime']['to']) && $this->filters['datetime']['to'] !== '')
      {
        if (isset($criterion))
        {
          $criterion->addAnd($c->getNewCriterion(CommentPeer::DATETIME, $this->filters['datetime']['to'], Criteria::LESS_EQUAL));
        }
        else
        {
          $criterion = $c->getNewCriterion(CommentPeer::DATETIME, $this->filters['datetime']['to'], Criteria::LESS_EQUAL);
        }
      }

      if (isset($criterion))
      {
        $c->add($criterion);
      }
    }
    
    if (isset($this->filters['approved_is_empty']))
    {
      $criterion = $c->getNewCriterion(CommentPeer::APPROVED, '');
      $criterion->addOr($c->getNewCriterion(CommentPeer::APPROVED, null, Criteria::ISNULL));
      $c->add($criterion);
    }
    else if (isset($this->filters['approved']) && $this->filters['approved'] !== '')
    {
      $c->add(CommentPeer::APPROVED, $this->filters['approved']);
    }
  }

  protected function addSortCriteria($c)
  {
    if ($sort_column = $this->getUser()->getAttribute('sort', null, 'sf_admin/comment/sort'))
    {
      $sort_column = CommentPeer::translateFieldName($sort_column, BasePeer::TYPE_FIELDNAME, BasePeer::TYPE_COLNAME);
      if ($this->getUser()->getAttribute('type', null, 'sf_admin/comment/sort') == 'asc')
      {
        $c->addAscendingOrderByColumn($sort_column);
      }
      else
      {
        $c->addDescendingOrderByColumn($sort_column);
      }
    }
  }

  protected function getLabels()
  {
    return array(
      'comment{name}' => 'Name:',
      'comment{url}' => 'Url:',
      'comment{content}' => 'Content:',
      'comment{approved}' => 'Approved:',      
      'comment{user}' => 'User:',      
    );
  }
  
  public function executeApprove()
  {
    $comment = CommentPeer::retrieveByPk($this->getRequestParameter('id'));
    $this->forward404Unless($comment instanceof Comment);
    
    $comment->setApproved(($this->getRequestParameter('status')) ? '1' : '0');
    $comment->save();
    
    return $this->redirect('@admin?module=comment&action=list');
  }  
}
